package cn.kelvin.adapter;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import cn.kelvin.adapter.Token.TokenType;

public class MyTokenStream implements TokenStream{
	private int tokenIndex=0;
	private List<Token> tokenCache = new ArrayList<>();
	InputStream in;

	@SuppressWarnings("resource")
	public MyTokenStream(InputStream in) {
		this.in = in;
		String input = new Scanner(in).nextLine();
		parseInput(input);
	}
	
//	@SuppressWarnings("resource")
//	public void readInput(){
//		String input = new Scanner(in).nextLine();
//		parseInput(input);
//	}
	
	private void parseInput(String input) {
		if(null==input || "".equals(input)){
			return;
		}
		int i=0;
		while(i<input.length()){
			char ch = input.charAt(i);
			switch (ch) {
			case '(':
				tokenCache.add(new Token(Token.TokenType.LPAR, String.valueOf(ch)));
				break;
			case ')':
				tokenCache.add(new Token(Token.TokenType.RPAR, String.valueOf(ch)));			
				break;
			case '+':
				tokenCache.add(new Token(Token.TokenType.PLUS, String.valueOf(ch)));
				break;
			case '-':
				tokenCache.add(new Token(Token.TokenType.MINUS, String.valueOf(ch)));
				break;
			case '*':
				tokenCache.add(new Token(Token.TokenType.MULT, String.valueOf(ch)));
				break;
			case '/':
				tokenCache.add(new Token(Token.TokenType.DIV, String.valueOf(ch)));
				break;
			default:
				try {
					Integer num = Integer.valueOf(String.valueOf(ch));
					tokenCache.add(new Token(Token.TokenType.INT, num));
				} catch (Exception e) {
//					e.printStackTrace();
				}
				break;
			}
			i++;
		}
	}

	@Override
	public Token getToken() throws IOException {
		if(tokenIndex<tokenCache.size()){
			return tokenCache.get(tokenIndex);
		}
		return new Token(TokenType.NONE, null);
	}

	@Override
	public void consumeToken() {
		tokenIndex ++;
	}
	
	
}
